<?php

namespace App\Admin\Extensions;

use App\Http\Controllers\ImageController;
use Encore\Admin\Admin;
use Encore\Admin\Exception\Handler;
use Encore\Admin\Media\MediaManager as BaseMediaManager;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\Adapter\Local;

class MediaManager extends BaseMediaManager
{

    public function __construct($path = '/')
    {
        $this->path = $path;

        $this->initStorage();
    }

    public function ls()
    {
        $data = parent::ls();

        return collect($data)
            ->filter(function ($item) {
                return basename($item['name']) !== ImageController::$cacheName;
            })->toArray();
    }

    private function initStorage()
    {
        $disk = static::config('disk', 'media_data');

        $this->storage = Storage::disk($disk);

        if (!$this->storage->getDriver()->getAdapter() instanceof Local) {
            Handler::error('Error', '[laravel-admin-ext/media-manager] only works for local storage.');
        }
    }

    public function getFilePreview($file)
    {
        switch ($this->detectFileType($file)) {
            case 'image':

                if ($this->storage->getDriver()->getConfig()->has('url')) {
                    $url     = $this->storage->url($file);
                    $preview = "<span class=\"file-icon has-img\"><img src=\"$url?size=small\" alt=\"Attachment\"></span>";
                } else {
                    $preview = '<span class="file-icon"><i class="fa fa-file-image-o"></i></span>';
                }
                break;

            case 'pdf':
                $preview = '<span class="file-icon"><i class="fa fa-file-pdf-o"></i></span>';
                break;

            case 'zip':
                $preview = '<span class="file-icon"><i class="fa fa-file-zip-o"></i></span>';
                break;

            case 'word':
                $preview = '<span class="file-icon"><i class="fa fa-file-word-o"></i></span>';
                break;

            case 'ppt':
                $preview = '<span class="file-icon"><i class="fa fa-file-powerpoint-o"></i></span>';
                break;

            case 'xls':
                $preview = '<span class="file-icon"><i class="fa fa-file-excel-o"></i></span>';
                break;

            case 'txt':
                $preview = '<span class="file-icon"><i class="fa fa-file-text-o"></i></span>';
                break;

            case 'code':
                $preview = '<span class="file-icon"><i class="fa fa-code"></i></span>';
                break;

            default:
                $preview = '<span class="file-icon"><i class="fa fa-file"></i></span>';
        }

        return $preview;
    }

}
